package mqtt

import (
	"log"
	"time"

	"gitee.com/pkg33/cfg"
	mqtt "github.com/eclipse/paho.mqtt.golang"
)

// MqttClient MQTT客户端
type MqttClient struct {
	client mqtt.Client
}

// MqttClientCfg MQTT客户端配置
type MqttClientCfg struct {
	Host     string `toml:"host"`
	Port     string `toml:"port"`
	Username string `toml:"username"`
	Password string `toml:"password"`
	ClientID string `toml:"client_id"`
}

// 默认配置实例
var defaultCfg = &MqttClientCfg{
	Host:     "localhost",
	Port:     "1883",
	Username: "root",
	Password: "password",
	ClientID: "clientid",
}

func NewMqttClient() *MqttClient {
	cfg.MustRegister("mqtt_client", defaultCfg)
	c := cfg.Get("mqtt_client").(*MqttClientCfg)
	opts := mqtt.NewClientOptions()
	opts.AddBroker("tcp://" + c.Host + ":" + c.Port)
	opts.SetClientID(c.ClientID)
	opts.SetUsername(c.Username)
	opts.SetPassword(c.Password)
	opts.SetAutoReconnect(true)
	opts.SetMaxReconnectInterval(1 * time.Second)
	client := mqtt.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		log.Fatal(token.Error())
	}
	return &MqttClient{
		client: client,
	}
}

func (me *MqttClient) Subscribe(topic string, callback mqtt.MessageHandler) error {
	token := me.client.Subscribe(topic, 1, callback)
	token.Wait()
	return token.Error()
}

func (me *MqttClient) Publish(topic string, payload any) error {
	token := me.client.Publish(topic, 1, false, payload)
	token.Wait()
	return token.Error()
}

func (me *MqttClient) Close() {
	me.client.Disconnect(250)
}
